package mychat.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;

public class ConnectionPools {
	private static final int MIN = 5;
	private static final String DB = "jdbc:mysql:"
			+ "//localhost/chat?user=weihua&password=noukey";
	private static int current = MIN;
	private static int bind = 0;

	private static ArrayList<MyCon> list = new ArrayList<MyCon>(MIN);
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			for (int i = 0; i < MIN; ++i) {
				Connection con1 = DriverManager.getConnection(DB);
				MyCon con = new MyCon(con1);
				list.add(con);
			}
		} catch (ClassNotFoundException e) {
			System.out.println("找不到数据库驱动程序！");
			System.exit(1);
		} catch (SQLException e) {
			System.out.println("数据库不存在或数据库用户名密码错误！");
			System.exit(1);
		}
	}

	public synchronized static Connection getConnection() {
		if (bind > current - 1) {
			try {
				MyCon con = new MyCon(DriverManager.getConnection(DB));
				con.setBind(true);
				list.add(con);
				++current;
				++bind;
				return con.getCon();
			} catch (SQLException e) {
				System.out.println("无法连接数据库！");
			}
		} else {
			for (MyCon con : list) {
				if (!con.isBind()) {
					con.setBind(true);
					++current;
					++bind;
					return con.getCon();
				}
			}
		}
		return null;
	}

	public static synchronized void freeConnectiopn(Connection con) {
		for(MyCon mycon : list){
			if(mycon.getCon()==con){
				mycon.setBind(false);
				--bind;
				break;
			}
		}
	}

	public static void close() {
		for (MyCon con : list) {
			if (con.isBind()) {
				System.out.println("还有连接绑定的连接！");
			}
			Connection con1 = con.getCon();
			try {
				if (!con1.isClosed()) {
					con1.close();
					con1 = null;
				}
			} catch (SQLException e) {

			}
		}
	}

}
